const app = getApp();
var wxCharts = require('../../utils/wxcharts.js');
var emsChart = null;
var bodyCircumferenceChart = null;
var bodyAdaptabilityChart = null;
var tichengfenChart = null;
var pbfChart = null;
var smmChart = null;
var vfiChart = null;
var strongIndexChart = null;
var bmrChart = null;
var teeChart = null;
var bmiChart = null;
var muscleChart = null;
var segmentalFatChart = null;
var whfrChart = null;
let windowWidth = 320;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    traineePhone: null,
    index: 0,
    title: 'EMS评估历史记录',
    emsEvaluations: [],
    bodyCircumferences: [],
    bodyAdaptabilities: [],
    bodyMeasurements: [],
    tabs: [{
      type: 'LOCALLY',
      text: '局部',
      checked: true
    }, {
      type: 'WHOLE',
      text: '整体',
      checked: false
    }],
    emsItems: [],
    bodyCircumferencesItems: [],
    bodyAdaptabilityItems: [{
      text: '平衡性',
      name: 'balance',
      checked: true
    }, {
      text: '柔韧性',
      name: 'flexibility',
      checked: true
    }, {
      text: '协调性',
      name: 'coordination',
      checked: true
    }, {
      text: '心肺功能',
      name: 'cardiorespiratory',
      checked: true
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const traineePhone = wx.getStorageSync('traineePhone');
    const bodyCircumferencesItems = app.globalData.bodyMeasurements;
    const emsItems = app.globalData.emsItems;
    bodyCircumferencesItems.forEach(function(item) {
      item.checked = true;
    });
    this.setData({
      traineePhone,
      bodyCircumferencesItems,
      emsItems
    });
    this.emsEvaluations();
    let res = wx.getSystemInfoSync();
    windowWidth = res.windowWidth;
    this.bodyMeasurements();
    this.bodyCircumferences();
    this.bodyAdaptabilities();
  },
  emsTypeChange: function(e) {
    const tabs = this.data.tabs;
    const value = e.detail.value;
    tabs.forEach(function(item) {
      if (item.type == value) {
        item.checked = true;
      } else {
        item.checked = false;
      }
    });
    this.setData({
      tabs
    });
    this.refleshEmsCharts();
  },
  positionChange: function(e) {
    const valueArr = e.detail.value;
    const emsItems = this.data.emsItems;
    emsItems.forEach(function(item) {
      if (valueArr.indexOf(item.columnName) >= 0) {
        item.checked = true;
      } else {
        item.checked = false;
      }
    });
    let selectCount = 0;
    emsItems.forEach(function(item) {
      if (item.checked == true) {
        selectCount++;
      }
    });
    if (selectCount < 1) {
      wx.showToast({
        title: '至少有一个显示的项目',
        icon: 'none'
      })
      return;
    }
    this.setData({
      emsItems
    });
    this.refleshEmsCharts();
  },
  bodyCircumferenceChange: function(e) {
    const bodyCircumferencesItems = this.data.bodyCircumferencesItems;
    const valueArr = e.detail.value;
    bodyCircumferencesItems.forEach(function(item) {
      if (valueArr.indexOf(item.columnName) >= 0) {
        item.checked = true;
      } else {
        item.checked = false;
      }
    });
    let selectCount = 0;
    bodyCircumferencesItems.forEach(function(item) {
      if (item.checked == true) {
        selectCount++;
      }
    });
    if (selectCount < 1) {
      wx.showToast({
        title: '至少有一个显示的项目',
        icon: 'none'
      })
      return;
    }
    this.setData({
      bodyCircumferencesItems
    });
    this.refleshBodyCircumferenceCharts();
  },
  refleshEmsCharts: function() {
    const tabs = this.data.tabs;
    const emsItems = this.data.emsItems;
    let type = null;
    tabs.forEach(function(item) {
      if (item.checked == true) {
        type = item.type;
      }
    });
    let index = 1;
    if (type == 'WHOLE') {
      index = 2;
    }
    const emsEvaluations = this.data.emsEvaluations;
    const series = [];
    const categories = [];
    emsEvaluations.forEach(function(item) {
      categories.push(item.emsDate);
    });
    emsItems.forEach(function(item) {
      if (item.checked == true) {
        const position = item.position;
        const serie = {
          name: position,
          data: []
        };
        emsEvaluations.forEach(function(ems) {
          serie.data.push(ems[item.columnName + index]);
        });
        series.push(serie);
      }
    });
    if (categories.length == 0 || series.length == 0) {
      return;
    }
    emsChart = new wxCharts({
      canvasId: 'emsChartCanvas',
      type: 'line',
      categories,
      series,
      yAxis: {
        title: 'EMS强度',
        min: 0
      },
      width: windowWidth,
      height: 400,
      extra: {
        lineStyle: 'curve'
      }
    });
  },
  refleshBodyCircumferenceCharts: function() {
    const bodyCircumferences = this.data.bodyCircumferences;
    const bodyCircumferencesItems = this.data.bodyCircumferencesItems;
    const series = [];
    const categories = [];
    bodyCircumferences.forEach(function(item) {
      categories.push(item.bodyDate);
    });
    bodyCircumferencesItems.forEach(function(item) {
      if (item.checked == true) {
        const name = item.name;
        const serie = {
          name,
          data: []
        };
        bodyCircumferences.forEach(function(ems) {
          serie.data.push(ems[item.columnName]);
        });
        series.push(serie);
      }
    });
    if (categories.length == 0 || series.length == 0) {
      return;
    }
    bodyCircumferenceChart = new wxCharts({
      canvasId: 'bodyCircumferenceChartCanvas',
      type: 'line',
      categories,
      series,
      yAxis: {
        title: '身体围度',
        min: 0
      },
      width: windowWidth,
      height: 400,
      extra: {
        lineStyle: 'curve'
      }
    });
  },
  refleshBodyAdaptabilityCharts: function() {
    const bodyAdaptabilityItems = this.data.bodyAdaptabilityItems;
    const bodyAdaptabilities = this.data.bodyAdaptabilities;
    const series = [];
    const categories = [];
    bodyAdaptabilities.forEach(function(item) {
      categories.push(item.bodyDate);
    });
    bodyAdaptabilityItems.forEach(function(item) {
      const name = item.text;
      const serie = {
        name,
        data: []
      };
      bodyAdaptabilities.forEach(function(ems) {
        serie.data.push(ems[item.name]);
      });
      series.push(serie);
    });
    if (categories.length == 0 || series.length == 0) {
      return;
    }
    bodyAdaptabilityChart = new wxCharts({
      canvasId: 'bodyAdaptabilityChartCanvas',
      type: 'line',
      categories,
      series,
      yAxis: {
        title: '体适能',
        min: 0
      },
      width: windowWidth,
      height: 400,
      extra: {
        lineStyle: 'curve'
      }
    });
  },
  refleshBodyMeasurementsCharts: function() {
    const bodyMeasurements = this.data.bodyMeasurements;
    //体成份
    const series = [];
    const categories = [];
    bodyMeasurements.forEach(function(item) {
      categories.push(item.bodyDate);
    });
    const weight = {
      name: '体重',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const fat = {
      name: '脂肪量',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const ffm = {
      name: '去脂体重',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const mineral = {
      name: '无机盐',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const muscle = {
      name: '肌肉量',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const protein = {
      name: '蛋白质',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const tbw = {
      name: '身体水分',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    bodyMeasurements.forEach(function(item) {
      weight.data.push(item.data.composition.weight.value || 0);
      fat.data.push(item.data.composition.fat.value || 0);
      ffm.data.push(item.data.composition.ffm.value || 0);
      mineral.data.push(item.data.composition.mineral.value || 0);
      muscle.data.push(item.data.composition.muscle.value || 0);
      protein.data.push(item.data.composition.protein.value || 0);
      tbw.data.push(item.data.composition.tbw.value || 0);
    });
    series.push(weight);
    series.push(fat);
    series.push(ffm);
    series.push(mineral);
    series.push(muscle);
    series.push(protein);
    series.push(tbw);
    if (categories.length == 0 || series.length == 0) {
      return;
    }
    tichengfenChart = new wxCharts({
      canvasId: 'tichengfenChartCanvas',
      type: 'line',
      categories,
      series,
      yAxis: {
        title: '体成分构成',
        min: 0
      },
      width: windowWidth,
      height: 280,
      extra: {
        lineStyle: 'curve'
      }
    });
    //肌肉节段分析
    const segmentalMuscleSeries = [];
    const tr = {
      name: '躯干',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const la = {
      name: '左臂',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const ll = {
      name: '左腿',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const ra = {
      name: '右臂',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    const rl = {
      name: '右腿',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    };
    bodyMeasurements.forEach(function(item) {
      tr.data.push(item.data.composition.segmental_muscle.tr.value || 0);
      la.data.push(item.data.composition.segmental_muscle.la.value || 0);
      ll.data.push(item.data.composition.segmental_muscle.ll.value || 0);
      ra.data.push(item.data.composition.segmental_muscle.ra.value || 0);
      rl.data.push(item.data.composition.segmental_muscle.rl.value || 0);
    });
    segmentalMuscleSeries.push(tr);
    segmentalMuscleSeries.push(ra);
    segmentalMuscleSeries.push(rl);
    segmentalMuscleSeries.push(la);
    segmentalMuscleSeries.push(ll);
    if (categories.length == 0 || segmentalMuscleSeries.length == 0) {
      return;
    }
    muscleChart = new wxCharts({
      canvasId: 'muscleChartCanvas',
      type: 'column',
      categories,
      series: segmentalMuscleSeries,
      yAxis: {
        title: '肌肉节段分析',
        min: 0
      },
      width: windowWidth,
      height: 280
    });
    //脂肪节段分析
    const segmentalFatSeries = [];
    const tr1 = {
      name: '躯干',
      data: [],
      format: function(val) {
        return val.toFixed(2) + '%';
      }
    };
    const la1 = {
      name: '左臂',
      data: [],
      format: function(val) {
        return val.toFixed(2) + '%';
      }
    };
    const ll1 = {
      name: '左腿',
      data: [],
      format: function(val) {
        return val.toFixed(2) + '%';
      }
    };
    const ra1 = {
      name: '右臂',
      data: [],
      format: function(val) {
        return val.toFixed(2) + '%';
      }
    };
    const rl1 = {
      name: '右腿',
      data: [],
      format: function(val) {
        return val.toFixed(2) + '%';
      }
    };
    bodyMeasurements.forEach(function(item) {
      tr1.data.push(item.data.composition.segmental_fat.tr.value || 0);
      la1.data.push(item.data.composition.segmental_fat.la.value || 0);
      ll1.data.push(item.data.composition.segmental_fat.ll.value || 0);
      ra1.data.push(item.data.composition.segmental_fat.ra.value || 0);
      rl1.data.push(item.data.composition.segmental_fat.rl.value || 0);
    });
    segmentalFatSeries.push(tr1);
    segmentalFatSeries.push(ra1);
    segmentalFatSeries.push(rl1);
    segmentalFatSeries.push(la1);
    segmentalFatSeries.push(ll1);
    if (categories.length == 0 || segmentalFatSeries.length == 0) {
      return;
    }
    segmentalFatChart = new wxCharts({
      canvasId: 'segmentalFatChartCanvas',
      type: 'column',
      categories,
      series: segmentalFatSeries,
      yAxis: {
        title: '脂肪节段分析',
        min: 0
      },
      width: windowWidth,
      height: 280
    });
    //腰臀脂肪比
    const whfrSeries = [{
      name: '腰臀脂肪比',
      data: [],
      format: function(val) {
        return val.toFixed(2) + '%';
      }
    }];
    bodyMeasurements.forEach(function(item) {
      whfrSeries[0].data.push(item.data.composition.whfr.value || 0);
    });
    if (categories.length == 0 || whfrSeries.length == 0) {
      return;
    }
    whfrChart = new wxCharts({
      canvasId: 'whfrChartCanvas',
      type: 'line',
      categories,
      series: whfrSeries,
      yAxis: {
        title: '腰臀脂肪比',
        min: 0
      },
      width: windowWidth,
      height: 150,
      extra: {
        lineStyle: 'curve'
      }
    });
    //身体参数
    //1，体脂率
    const pbfSeries = [{
      name: '体脂率',
      data: [],
      format: function(val) {
        return val.toFixed(2) + '%';
      }
    }];
    bodyMeasurements.forEach(function(item) {
      pbfSeries[0].data.push(item.data.composition.pbf.value || 0);
    });
    if (categories.length == 0 || pbfSeries.length == 0) {
      return;
    }
    pbfChart = new wxCharts({
      canvasId: 'pbfChartCanvas',
      type: 'column',
      categories,
      series: pbfSeries,
      yAxis: {
        title: '体脂率',
        min: 0
      },
      width: windowWidth,
      height: 150
    });
    //2，骨骼肌
    const smmSeries = [{
      name: '骨骼肌',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kg';
      }
    }];
    bodyMeasurements.forEach(function(item) {
      smmSeries[0].data.push(item.data.composition.smm.value || 0);
    });
    if (categories.length == 0 || smmSeries.length == 0) {
      return;
    }
    smmChart = new wxCharts({
      canvasId: 'smmChartCanvas',
      type: 'column',
      categories,
      series: smmSeries,
      yAxis: {
        title: '骨骼肌',
        min: 0
      },
      width: windowWidth,
      height: 150
    });
    //3，内脏脂肪
    const vfiSeries = [{
      name: '内脏脂肪',
      data: []
    }];
    bodyMeasurements.forEach(function(item) {
      vfiSeries[0].data.push(item.data.composition.vfi.value || 0);
    });
    if (categories.length == 0 || vfiSeries.length == 0) {
      return;
    }
    vfiChart = new wxCharts({
      canvasId: 'vfiChartCanvas',
      type: 'column',
      categories,
      series: vfiSeries,
      yAxis: {
        title: '内脏脂肪',
        min: 0
      },
      width: windowWidth,
      height: 150
    });
    //4，健壮指数
    const strongIndexSeries = [{
      name: '健壮指数',
      data: []
    }];
    bodyMeasurements.forEach(function(item) {
      strongIndexSeries[0].data.push(item.data.composition.strong_index.value || 0);
    });
    if (categories.length == 0 || strongIndexSeries.length == 0) {
      return;
    }
    strongIndexChart = new wxCharts({
      canvasId: 'strongIndexChartCanvas',
      type: 'line',
      categories,
      series: strongIndexSeries,
      yAxis: {
        title: '健壮指数',
        min: 0
      },
      width: windowWidth,
      height: 150,
      extra: {
        lineStyle: 'curve'
      }
    });
    //5，基础代谢
    const bmrSeries = [{
      name: '基础代谢',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kcal';
      }
    }];
    bodyMeasurements.forEach(function(item) {
      bmrSeries[0].data.push(item.data.composition.bmr.value || 0);
    });
    if (categories.length == 0 || bmrSeries.length == 0) {
      return;
    }
    bmrChart = new wxCharts({
      canvasId: 'bmrChartCanvas',
      type: 'line',
      categories,
      series: bmrSeries,
      yAxis: {
        title: '基础代谢',
        min: 0
      },
      width: windowWidth,
      height: 150,
      extra: {
        lineStyle: 'curve'
      }
    });
    //6，总能量消耗
    const teeSeries = [{
      name: '总能量消耗',
      data: [],
      format: function(val) {
        return val.toFixed(2) + 'kcal';
      }
    }];
    bodyMeasurements.forEach(function(item) {
      teeSeries[0].data.push(item.data.composition.tee.value || 0);
    });
    setTimeout(function() {
      if (categories.length == 0 || teeSeries.length == 0) {
        return;
      }
      teeChart = new wxCharts({
        canvasId: 'teeChartCanvas',
        type: 'line',
        categories,
        series: teeSeries,
        yAxis: {
          title: '总能量消耗',
          min: 0
        },
        width: windowWidth,
        height: 150,
        extra: {
          lineStyle: 'curve'
        }
      });
    }, 2000);
    //7,身体质量指数
    const bmiSeries = [{
      name: '身体质量指数',
      data: []
    }];
    bodyMeasurements.forEach(function(item) {
      bmiSeries[0].data.push(item.data.composition.bmi.value || 0);
    });
    setTimeout(function() {
      if (categories.length == 0 || bmiSeries.length == 0) {
        return;
      }
      bmiChart = new wxCharts({
        canvasId: 'bmiChartCanvas',
        type: 'line',
        categories,
        series: bmiSeries,
        yAxis: {
          title: '身体质量指数',
          min: 0
        },
        width: windowWidth,
        height: 150,
        extra: {
          lineStyle: 'curve'
        }
      });
    }, 2000);
  },
  onPullDownRefresh: function() {
    const index = this.data.index;
    const that = this;
    switch (index) {
      case 0:
      case '0':
        that.emsEvaluations();
        break;
      case 1:
      case '1':
        that.bodyMeasurements();
        break;
      case 2:
      case '2':
        that.bodyCircumferences();
        break;
      case 3:
      case '3':
        that.bodyAdaptabilities();
        break;
    }
  },
  changeTab: function(e) {
    const index = e.currentTarget.dataset.index;
    const title = e.currentTarget.dataset.title;
    const that = this;
    this.setData({
      index,
      title
    });
    wx.setNavigationBarTitle({
      title: title + '历史记录'
    });
    //重新渲染charts
    switch (index) {
      case '0':
      case 0:
        that.refleshEmsCharts();
        break;
      case '1':
      case 1:
        that.refleshBodyMeasurementsCharts();
        break;
      case '2':
      case 2:
        that.refleshBodyCircumferenceCharts();
        break;
      case '3':
      case 3:
        that.refleshBodyAdaptabilityCharts();
        break;
    }
  },
  emsEvaluations: function() {
    const traineePhone = this.data.traineePhone;
    const url = app.globalData.url;
    const that = this;
    wx.showNavigationBarLoading();
    wx.request({
      url: url + '/train/queryEmsAssessment/' + traineePhone,
      success: function(response) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (response.data.success) {
          that.setData({
            emsEvaluations: response.data.content
          });
          that.refleshEmsCharts();
        }
      }
    })
  },
  bodyCircumferences: function() {
    const traineePhone = this.data.traineePhone;
    const url = app.globalData.url;
    const that = this;
    wx.showNavigationBarLoading();
    wx.request({
      url: url + '/train/queryBodyCircumference/' + traineePhone,
      success: function(response) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (response.data.success) {
          that.setData({
            bodyCircumferences: response.data.content
          });
          that.refleshBodyCircumferenceCharts();
        }
      }
    })
  },
  bodyAdaptabilities: function() {
    const traineePhone = this.data.traineePhone;
    const url = app.globalData.url;
    const that = this;
    wx.showNavigationBarLoading();
    wx.request({
      url: url + '/train/queryBodyAdaptability/' + traineePhone,
      success: function(response) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (response.data.success) {
          that.setData({
            bodyAdaptabilities: response.data.content
          });
          that.refleshBodyAdaptabilityCharts();
        }
      }
    })
  },
  bodyMeasurements: function() {
    const traineePhone = this.data.traineePhone;
    const url = app.globalData.url;
    const that = this;
    wx.showNavigationBarLoading();
    wx.request({
      url: url + '/xone/findHistory/' + traineePhone,
      success: function(response) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (response.data.success) {
          that.setData({
            bodyMeasurements: response.data.content.reverse()
          });
          that.refleshBodyMeasurementsCharts();
        }
      }
    })
  }
})